package kr.org.mirim;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;

public class MySurfaceView extends SurfaceView implements Callback,	Runnable {
	private SurfaceHolder holder;
	private Thread thread;
	public boolean isRun; 
	private Canvas canvas;
	private int x;
	private int y;
	private int bugX;
	private int bugY;
	private Bitmap bug[] = new Bitmap[2];
	private int frameCount;
	
	public MySurfaceView(Context context){
		super(context);	
		holder = getHolder();
		holder.addCallback(this);
		bug[0]=BitmapFactory.decodeResource(getResources(), R.drawable.red1);
		bug[1]=BitmapFactory.decodeResource(getResources(), R.drawable.red2);
	}
	
	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		thread = new Thread(this);
		thread.start();
		
	}

	@Override
	public void run() {
		isRun = true;
		while(isRun){
		canvas = holder.lockCanvas();

		drawWhiteBackground();
		
		drawMe();
		
		calcBugPosition();
		
		drawBug();
		
		holder.unlockCanvasAndPost(canvas);
		
		frameCount++;
		
		try {
			Thread.sleep(100);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	}
	private void drawWhiteBackground(){
		Paint paint = new Paint();
		paint.setColor(Color.WHITE);
		paint.setStyle(Paint.Style.FILL);
		canvas.drawRect(new Rect(0,0,getWidth(),getHeight()), paint);
	}
	
	private void drawMe(){
		Bitmap bitmap =BitmapFactory.decodeResource(getResources(), R.drawable.blue);
		canvas.drawBitmap(bitmap, x,y, null);
	}
	
	private void drawBug(){
		canvas.drawBitmap(bug[frameCount%2], bugX, bugY,null);
		
	}
	
	private void calcBugPosition(){
		if(x>bugX){
			bugX += 10;
		}
		else if(x<bugX){
			bugX -=10;
		}
		
		if(x>bugY){
			bugY += 10;
		}
		else if(x<bugY){
			bugY -=10;
		}
	}
	
	public boolean onTouchEvent(MotionEvent event){
		x=(int)event.getX();
		y=(int)event.getY();
		return true;
	}
	
	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		// TODO Auto-generated method stub
		
	}
}
